import { useEffect, useMemo, useState } from "react";
import { Button, Space, Table, Input, Modal, Form, App } from 'antd';
import { PlusOutlined } from '@ant-design/icons'
import type { TableProps } from 'antd';
import { addJobApi, deleteJobApi, findJobApi, updateJobApi } from "@/apis/jobApi";
import type { GetProps } from 'antd';
import ContentCard from "@/components/card";
type SearchProps = GetProps<typeof Input.Search>;

// 定义数组中每一条数据的类型
interface DataType {
    _id: string;
    name: string;
    desc: string;
}


const JobManage = () => {
    // 表格的列配置
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '职务名称',
            dataIndex: 'name',   // 设置当前这一列要渲染的数据的属性名
            key: 'name',
            render: (name: string) => {
                return <a>{name}</a>;
            },
        },
        {
            title: '职务描述',
            dataIndex: 'desc',
            key: 'desc',
        },
        {
            title: '操作',
            dataIndex: '_id',
            key: 'action',
            render: (_id: any, item: any) => (
                <Space>
                    <a onClick={() => onDelete(_id)}>删除</a>
                    <a onClick={() => onUpdate(item)}>修改</a>
                </Space>
            ),
        },
    ];

    // 表格的数据
    const [jobData, setJobData] = useState<{ rows: DataType[], total: number }>({
        rows: [],
        total: 0
    });
    // 搜索参数
    const [searchData, setSearchData] = useState({ searchValue: '' })
    // 分页参数
    const [pageData, setPageData] = useState({ currentPage: 1, pageSize: 5 })
    // 弹窗开关状态
    const [open, setOpen] = useState(false);
    // 保存当前要修改的数据
    const [updateItem, setUpdateItem] = useState<any>({});

    const [form] = Form.useForm();
    const { message, modal } = App.useApp();

    // 生命周期：组件挂载完成执行一次、数组中的任意数据发生改变执行
    useEffect(() => {
        findJob();
    }, [searchData, pageData])

    const title = useMemo(() => {
        // if(updateItem._id) {
        //     return '编辑职务';
        // }
        // return '添加职务';
        return updateItem._id ? '编辑职务' : '添加职务';
    }, [updateItem])

    // 获取、搜索、分页
    const findJob = async () => {
        const res = await findJobApi({
            ...searchData,
            ...pageData
        });
        if (res.code == 200) {
            setJobData(res.data);
        }
    }

    // 数组的删除
    const onDelete = (_id: string) => {
        modal.confirm({
            title: '警告',
            content: '该数据删除后不可恢复，确认删除?',
            onOk() {
                deleteJobApi({ _id })
                    .then(res => {
                        if (res.code == 200) {
                            findJob();
                            message.success('删除成功')
                        } else {
                            message.error(res.message);
                        }
                    })
            },
            onCancel() {
            },
        })



    }
    // 数组的修改：map
    const onUpdate = (item: any) => {
        setOpen(true);
        // 表单回显
        form.setFieldsValue(item);
        // 把修改的数据保存的state中
        setUpdateItem({ ...item });
    }

    // 搜索框的事件
    const onSearch: SearchProps['onSearch'] = (value) => {
        setSearchData({
            searchValue: value
        })
    };

    const onOk = () => {
        const formData = form.getFieldsValue();
        if (updateItem._id) {
            updateJobApi({
                ...updateItem,
                ...formData
            }).then(res => {
                if (res.code == 200) {
                    onCancel();  // 关闭弹窗
                    findJob();   // 更新列表
                    message.success('修改成功')
                } else {
                    message.error(res.message);
                }
            })
        } else {
            addJobApi(formData)
                .then(res => {
                    if (res.code == 200) {
                        onCancel();  // 关闭弹窗
                        findJob();   // 更新列表
                        message.success('新增成功')
                    } else {
                        message.error(res.message);
                    }
                })
        }
    }

    const onCancel = () => {
        setOpen(false);
        // 清空表单
        setUpdateItem({});
        form.resetFields();
    }

    // 当用户进行分页操作时
    const onPageChange = (currentPage: number, pageSize: number) => {
        setPageData({
            currentPage, pageSize
        })
    }

    return (
        <>
            <ContentCard title="职务管理">
                <div className="flex-bt" style={{ marginBottom: 15 }}>
                    <Input.Search allowClear style={{ width: 300 }} onSearch={onSearch} />
                    <Space>
                        <Button type="primary" icon={<PlusOutlined />} onClick={() => setOpen(true)}>
                            新增职务
                        </Button>
                        <Button color="primary" variant="outlined">批量删除</Button>
                    </Space>
                </div>

                <Table<DataType> columns={columns} dataSource={jobData.rows} rowKey="_id" pagination={{
                    total: jobData.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    pageSizeOptions: [5, 10, 20, 50],
                    showTotal: total => `共有${total}条数据`,
                    onChange: onPageChange
                }} />
            </ContentCard>

            {/* 新增弹窗  */}
            <Modal
                width={500}
                title={title}
                open={open}
                onOk={onOk}
                onCancel={onCancel}
            >

                <Form form={form} name="job" labelCol={{ style: { width: 80 } }} style={{ marginTop: 20 }} >
                    <Form.Item label="职务名称" name="name" rules={[
                        { required: true, message: '职务名称不能为空' }
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="职务描述" name="desc">
                        <Input.TextArea rows={4} />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export default JobManage